<?php
/**
 * Created by PhpStorm.
 * User: dumbledore
 * Date: 2017/12/20
 * Time: 上午9:38
 */

defined('BASEPATH') or exit('No direct script access allowed');

function send_msg($tel, $msg, $code, $apikey)
{
    // 发送短信
    $error_msg = '对不起，短信发送失败，请联系服务商';
    $res       = false;
    try
    {
        $res = send_message($tel, $msg, $apikey);
    } catch (\Exception $e) {
        $error_msg = $e->getMessage();
    }

    if ($res) {
        $data1['time']           = date("Y-m-d H:i:s");
        $data1['code']           = $code;
        $_SESSION[$tel . "code"] = json_encode($data1);
        return array('status' => 1, 'msg' => 'success');
    }
    return array('status' => 0, 'msg' => $error_msg);
}

// 发送短信使用
function send_message($tel, $msg, $apikey)
{
    header("Content-Type:text/html;charset=utf-8");
    $mobile = $tel;
    $text   = $msg;
    $ch     = curl_init();

    /* 设置验证方式 */
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8',
        'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));
    /* 设置返回结果为流 */
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

    /* 设置超时时间*/
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);

    /* 设置通信方式 */
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

// 取得用户信息
    //    $json_data = get_user($ch,$apikey);
    //    if(json_decode($json_data,true)['code'] != 0)
    //    {
    //        log_message('error','短信发送失败,设置错误：'.$json_data);
    //    }

// 发送短信
    $data      = array('text' => $text, 'apikey' => $apikey, 'mobile' => $mobile);
    $json_data = send($ch, $data);
    $array     = json_decode($json_data, true);
    if ($array['code'] == 0) {
        return true;
    } else {
        log_message('error', '短信发送失败：' . json_encode($array));
        throw new Exception($array['msg']);
    }

}

//获得账户
function get_user($ch, $apikey)
{
    curl_setopt($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/user/get.json');
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query(array('apikey' => $apikey)));
    $result = curl_exec($ch);
    $error  = curl_error($ch);
    checkErr($result, $error);
    return $result;
}
function send($ch, $data)
{
    curl_setopt($ch, CURLOPT_URL, 'https://sms.yunpian.com/v2/sms/single_send.json');
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    $result = curl_exec($ch);
    $error  = curl_error($ch);
    checkErr($result, $error);
    return $result;
}

function checkErr($result, $error)
{
    if ($result === false) {
        log_message('error', '短信发送错误：' . $error);
    } else {
        //echo '操作完成没有任何错误';
    }
}

//生成随机验证码
function generate_code($length = 6)
{
    return rand(pow(10, ($length - 1)), pow(10, $length) - 1);
}

// 验证手机号码
function is_mobile($str)
{
    return preg_match("/^1[34578]{1}\d{9}$/", $str);
}

// 校验入参
function check_param($fl, $params)
{
    if (!$params || !is_array($params)) {
        return false;
    }
    foreach ($params as $p) {
        if (!isset($fl[$p]) || !$fl[$p]) {
            return false;
        }
    }
    return true;
}

/**
 * 判断是否为合法的身份证号码
 * @param $mobile
 * @return int
 */
function isCreditNo($vStr)
{
    $vCity = array(
        '11', '12', '13', '14', '15', '21', '22',
        '23', '31', '32', '33', '34', '35', '36',
        '37', '41', '42', '43', '44', '45', '46',
        '50', '51', '52', '53', '54', '61', '62',
        '63', '64', '65', '71', '81', '82', '91',
    );
    if (!preg_match('/^([\d]{17}[xX\d]|[\d]{15})$/', $vStr)) {
        return false;
    }

    if (!in_array(substr($vStr, 0, 2), $vCity)) {
        return false;
    }

    $vStr    = preg_replace('/[xX]$/i', 'a', $vStr);
    $vLength = strlen($vStr);
    if ($vLength == 18) {
        $vBirthday = substr($vStr, 6, 4) . '-' . substr($vStr, 10, 2) . '-' . substr($vStr, 12, 2);
    } else {
        $vBirthday = '19' . substr($vStr, 6, 2) . '-' . substr($vStr, 8, 2) . '-' . substr($vStr, 10, 2);
    }
    if (date('Y-m-d', strtotime($vBirthday)) != $vBirthday) {
        return false;
    }

    if ($vLength == 18) {
        $vSum = 0;
        for ($i = 17; $i >= 0; $i--) {
            $vSubStr = substr($vStr, 17 - $i, 1);
            $vSum += (pow(2, $i) % 11) * (($vSubStr == 'a') ? 10 : intval($vSubStr, 11));
        }
        if ($vSum % 11 != 1) {
            return false;
        }

    }
    return true;
}

// 生成订单
function trade_no()
{
    list($usec, $sec) = explode(" ", microtime());
    $usec             = substr(str_replace('0.', '', $usec), 0, 4);
    $str              = rand(10, 99);
    return date("YmdHis") . $usec . $str;
}

/**
 * 计算两个坐标之间的距离(米)
 * @param float $fP1Lat 起点(纬度)
 * @param float $fP1Lon 起点(经度)
 * @param float $fP2Lat 终点(纬度)
 * @param float $fP2Lon 终点(经度)
 * @return int
 */
function distanceBetween($fP1Lat, $fP1Lon, $fP2Lat, $fP2Lon)
{
    $fEARTH_RADIUS = 6378137;
    //角度换算成弧度
    $fRadLon1 = deg2rad($fP1Lon);
    $fRadLon2 = deg2rad($fP2Lon);
    $fRadLat1 = deg2rad($fP1Lat);
    $fRadLat2 = deg2rad($fP2Lat);
    //计算经纬度的差值
    $fD1 = abs($fRadLat1 - $fRadLat2);
    $fD2 = abs($fRadLon1 - $fRadLon2);
    //距离计算
    $fP = pow(sin($fD1 / 2), 2) +
    cos($fRadLat1) * cos($fRadLat2) * pow(sin($fD2 / 2), 2);
    return intval($fEARTH_RADIUS * 2 * asin(sqrt($fP)) + 0.5);
}

/**
 * 接口请求
 */
//参数1：访问的URL，参数2：post数据(不填则为GET)，参数3：提交的$cookies,参数4：是否返回$cookies
function curl_request($url, $post = '', $cookie = '', $returnCookie = 0)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
    curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
    if ($post) {
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
    }
    if ($cookie) {
        curl_setopt($curl, CURLOPT_COOKIE, $cookie);
    }
    curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
    curl_setopt($curl, CURLOPT_TIMEOUT, 10);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $data = curl_exec($curl);
    if (curl_errno($curl)) {
        return curl_error($curl);
    }
    curl_close($curl);
    if ($returnCookie) {
        list($header, $body) = explode("\r\n\r\n", $data, 2);
        preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
        $info['cookie']  = substr($matches[1][0], 1);
        $info['content'] = $body;
        return $info;
    } else {
        return $data;
    }
}

// 两个日期相差天数
function diffBetweenTwoDays($day1, $day2)
{
    $second1 = strtotime($day1);
    $second2 = strtotime($day2);

    if ($second1 < $second2) {
        $tmp     = $second2;
        $second2 = $second1;
        $second1 = $tmp;
    }
    return ceil(($second1 - $second2) / 86400);
}

//随机字母
function randomLetters($length)
{
    $chars = 'abcdefghijklmnpqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ';
    $hash  = '';
    $max   = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

//随机数字
function randomNumber($length)
{
    $chars = '0123456789';
    $hash  = '';
    $max   = strlen($chars) - 1;
    for ($i = 0; $i < $length; $i++) {
        $hash .= $chars[mt_rand(0, $max)];
    }
    return $hash;
}

//随机字符串
function random($length, $chars = "")
{
    $length = isset($length) ? $length : '6';
    if (!$chars) {
        $chars = randomLetters(2) . randomNumber(8);
        return str_shuffle($chars);
    } else {
        $hash = '';
        $max  = strlen($chars) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $chars[mt_rand(0, $max)];
        }
        return $hash;
    }

}
